package com.cy.stone.system.application.impl;

import com.cy.stone.common.errorcode.SysErrorCode;
import com.cy.stone.system.application.RoleApi;
import com.cy.stone.system.domain.clientobject.role.RoleCO;
import com.cy.stone.system.infrastructure.database.entity.RoleEntity;
import com.cy.stone.system.infrastructure.database.service.IRoleService;
import com.feiniaojin.gracefulresponse.GracefulResponseException;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Optional;

import static com.cy.stone.system.infrastructure.database.table.RoleTableDef.ROLE_ENTITY;

/**
 * 角色接口实现类
 * @author Wings
 * @since 2023-12-10
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class RoleApiImpl implements RoleApi {

    private final IRoleService roleService;

    @Override
    public void addRole(RoleCO roleCO) {
        // 校验角色码或者角色名是否已经存在
        Optional<RoleEntity> role = roleService.getOneOpt(QueryWrapper.create().from(ROLE_ENTITY)
                .where(ROLE_ENTITY.ROLE_CODE.eq(roleCO.getRoleCode()))
                .or(ROLE_ENTITY.ROLE_NAME.eq(roleCO.getRoleName())));
        if (role.isPresent()) {
            log.error(roleCO.getRoleCode() + "-" + roleCO.getRoleName() + "的角色码或者角色名已存在");
            throw new GracefulResponseException(SysErrorCode.ROLE_EXIST.getCode(), SysErrorCode.ROLE_EXIST.getMessage());
        } else {
            RoleEntity roleEntity = RoleCO.toAddEntity(roleCO);
            roleService.save(roleEntity);
        }
    }

    @Override
    public void editRole(RoleCO roleCO) {
        // 校验角色是否存在
        Optional<RoleEntity> role = roleService.getByIdOpt(roleCO.getId());
        if (role.isPresent()) {
            RoleEntity roleEntity = role.get();
            RoleCO.updateEntity(roleCO, roleEntity);
            roleService.updateById(roleEntity);
        } else {
            log.error("ID:" + roleCO.getId() + "角色不存在");
            throw new GracefulResponseException(SysErrorCode.ROLE_NOT_EXIST.getCode(), SysErrorCode.ROLE_NOT_EXIST.getMessage());
        }
    }
}
